package com.shizhan.control;

import com.shizhan.entity.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class Read {
    private static Map<String, Data> map = new HashMap<String, Data>();

    public static Map<String,Data> readData() {
        File file = new File("port (2).xlsx");
        Workbook wb = null;
        Sheet sheet = null;
        if (file.exists()) {
            try {
                wb = new XSSFWorkbook(file);
                sheet = wb.getSheetAt(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 1; i <= rows; i++) {
            Row row = sheet.getRow(i);
            if (isRowEmpty(row)){
                break;
            }
            Data data = new Data();
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++){
                row.getCell(j).setCellType(CellType.STRING);
            }
            data.setName(row.getCell(2).getStringCellValue());
            data.setPhone(row.getCell(3).getStringCellValue());
            data.setPort(row.getCell(0).getStringCellValue());
            data.setPassword(row.getCell(1).getStringCellValue());
//            System.out.println(data.getPort());
            map.put(data.getPhone(),data);
        }
//        System.out.println(map.size());
        return map;
    }
    public static boolean isRowEmpty(Row row){
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() != CellType.BLANK){
                return false;
            }
        }
        return true;
    }
}
